import { computed, reactive } from 'vue'
import { getSizeCfg, isIE } from './utils'

export default function useCropperState(props: { size: string; containerSize: string }) {
  /** 图片原始尺寸 */
  const natural = reactive({
    width: 0,
    height: 0
  })

  /** 代理操作图片 */
  const proxy = reactive({
    width: 0,
    height: 0,
    left: 0,
    top: 0,
    scale: 1 // 缩放
  })

  /** 容器尺寸 */
  const container = computed(() => getSizeCfg(props.containerSize))

  /** 对话框宽度 */
  const dialogWidth = computed(() => container.value.width + 16 * 2)

  /** 裁剪尺寸 */
  const crop = computed(() => getSizeCfg(props.size))

  /** 裁剪区域 */
  const area = computed(() => {
    const { width: cw, height: ch } = crop.value
    const { width: tw, height: th } = container.value
    let width, height

    if (cw > ch) {
      width = tw * 0.8
      height = (width / cw) * ch
    } else {
      height = th * 0.8
      width = (height / ch) * cw
    }

    return { width, height }
  })

  /** 间距 */
  const space = computed(() => {
    const { width: cw, height: ch } = container.value
    const { width: aw, height: ah } = area.value
    return {
      x: (cw - aw) / 2,
      y: (ch - ah) / 2
    }
  })

  /** 原点 */
  const o = computed(() => {
    const { width: cw, height: ch } = container.value

    return {
      top: ch / 2,
      left: cw / 2
    }
  })

  /** 定位范围 */
  const range = computed(() => {
    const { width: cw, height: ch } = container.value
    const { width: pw, height: ph } = proxy
    const { x: spaceX, y: spaceY } = space.value

    if (isIE) {
      const top = ch - spaceY - ph
      const left = cw - spaceX - pw

      return {
        maxTop: Math.max(top, spaceY),
        minTop: Math.min(top, spaceY),
        maxLeft: Math.max(left, spaceX),
        minLeft: Math.min(left, spaceX)
      }
    }

    return {
      maxTop: ch - spaceY,
      minTop: spaceY - ph,
      maxLeft: cw - spaceX,
      minLeft: spaceX - pw
    }
  })

  /** 初始缩放 */
  const initScale = computed(() => {
    const { width: aw, height: ah } = area.value
    const { width: nw, height: nh } = natural
    const minX = aw / nw
    const minY = ah / nh

    return Math.max(minX, minY)
  })

  /** 状态 */
  return reactive({
    /** 图片原始尺寸 */
    natural,

    /** 容器尺寸 */
    container,

    /** 代理操作图片 */
    proxy,

    /** 对话框宽度 */
    dialogWidth,

    /** 裁剪尺寸 */
    crop,

    /** 裁剪区域 */
    area,

    /** 间距 */
    space,

    /** 原点 */
    o,

    /** 定位范围 */
    range,

    /** 初始缩放 */
    initScale
  })
}
